// ==UserScript==
// @name         get-cart
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  get specific item
// @author       Coolman
// @match        https://cart.taobao.com/cart.htm*
// @match        https://buy.tmall.com/order/confirm_order.htm*
// @grant        none
// ==/UserScript==
(() => {
    'use strict';

    // 生活终于要对我这只小猫咪🐱下手了～
    // https://cart.taobao.com/cart.htm*
    const moument = '2019-11-11 21:00'; // 抢购时间
    const keyword = '天猫精灵';

    const ms = +new Date(moument); // 抢购时间毫秒值
    const pre = +new Date(ms - 1000 * 5); // 提前 5 秒钟准备
    const end = +new Date(ms + 1000 * 60 * 2); // 二分钟之后结束

    // 获取服务器时间戳
    const getServerTime = async () => {
        return +new Date((await fetch(`#${ +new Date() }`, {
            method: 'head',
        }).then((res) => res.headers)).get("Date"));
    };

    window.onload = () => {
        if (location.href.startsWith('https://buy.tmall.com/order/confirm_order.htm')) {
            const submitBtn = document.querySelector('#submitOrderPC_1 a.go-btn');
            submitBtn && submitBtn.click();
            console.info('提交成功');
        } else {
            const footer = document.querySelector('#J_SiteFooter');
            if (footer) {
                for (let i = 0; i < 5; i++) {
                    setTimeout(() => {
                        footer.scrollIntoView();
                    }, 200 * i);
                }
            }
        }
    };

    // 咱也没买过茅台，不知道是不是这个流程
    const doTask = () => {
        document.querySelectorAll('ul.item-content').forEach((item) => {
            if (item.querySelector('div.item-basic-info').innerText.includes(keyword)) {
                const ckb = item.querySelector('input.J_CheckBoxItem');
                if (ckb) {
                    if (!ckb.checked) {
                        ckb.click();
                    }
                    const submitBtn = document.querySelector('div.btn-area > a.submit-btn');
                    submitBtn && submitBtn.click();
                }
                return;
            }
        });
    };

    const intervalId = setInterval(() => {
        getServerTime().then(now => {
            console.log(`server time: ${ now }`);
            // 结束了
            if (now >= end) {
                console.info(`it's time to end.`);
                clearInterval(intervalId);
                return;
            }
            // 准备时间
            if (now >= pre) {
                console.log(`it's time to go...`);
                if (now >= ms) {
                    doTask();
                }
            } else {
                console.info(`it's too early.`);
                clearInterval(intervalId);
                return;
            }
        });
    }, 800);
})();
